<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="设备类型" prop="type">
        <el-select v-model="queryParams.type" @change="handleQuery" placeholder="请选择…" clearable>
          <el-option v-for="dict in dict.type.equipment_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="设备编号" prop="no">
        <el-input v-model="queryParams.no" placeholder="请输入设备编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="是否分配" prop="fp">
        <el-select v-model="queryParams.fp" @change="handleQuery" placeholder="请选择…" clearable>
          <el-option label="未分配" value="0" />
          <el-option label="已分配" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="分配医院" prop="hospitalId">
        <el-select v-model="queryParams.hospitalId" placeholder="请选择医院" clearable filterable @change="queryHospitalChange">
          <el-option v-for="data in hospitalOptions" :key="data.value" :label="data.label" :value="data.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="分配科室" prop="deptId">
        <el-select v-model="queryParams.deptId" placeholder="请选择科室" clearable filterable @change="handleQuery">
          <el-option v-for="data in deptOptions" :key="data.value" :label="data.label" :value="data.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['equipment:info:add']" >新增</el-button>
      </el-col>
      <el-col :span="1.5" v-show="change.type === ''">
        <el-button type="success" plain icon="el-icon-edit" size="mini" @click="handleBtn('distribution')" v-hasPermi="['equipment:info:distribution']">分配</el-button>
      </el-col>
      <el-col :span="1.5" v-show="change.type === ''">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" @click="handleBtn('recovery')" v-hasPermi="['equipment:info:recovery']" >回收</el-button>
      </el-col>
      <el-col :span="1.5" v-show="change.type !== ''">
        <el-button type="success" plain icon="el-icon-check" @click="handleChange" :disabled="multiple" size="mini">确定</el-button>
      </el-col>
      <el-col :span="1.5" v-show="change.type !== ''">
        <el-button plain icon="el-icon-close" size="mini" @click="handleChangeCancel" >取消</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-upload2" size="mini" @click="handleImport" v-hasPermi="['equipment:info:import']" >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['equipment:info:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" ref="equipmentTable" :data="infoList" @selection-change="handleSelectionChange">
      <el-table-column v-if="change.type !== ''" type="selection" :selectable="isSelectable" width="55" align="center" />
      <el-table-column label="设备编号" align="center" prop="equipmentNo" />
      <el-table-column label="设备类型" align="center" prop="type" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.equipment_type" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column label="是否分配" align="center" prop="feipei" >
        <template slot-scope="scope">
          <el-tag v-if="scope.row.fenpei === '0'" size="mini" type="info">未分配</el-tag>
          <el-tag v-if="scope.row.fenpei === '1'" size="mini" type="success">已分配</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="分配医院" align="center" prop="hospital" />
      <el-table-column label="分配科室" align="center" prop="dept" />
      <el-table-column label="剩余次数" align="center" prop="cs" width="120" />
      <el-table-column label="是否测试设备" align="center" prop="test" width="120" >
        <template slot-scope="scope">
          <el-popconfirm @confirm="doChange(scope.row.hosEqId, '0')" v-if="scope.row.test === '1'"
                         :title="'是否将设备'+ scope.row.equipmentNo +'设置为非测试设备？'" >
            <el-button type="text" slot="reference">是</el-button>
          </el-popconfirm>

          <el-popconfirm @confirm="doChange(scope.row.hosEqId, '1')" v-if="scope.row.test === '0'"
                         :title="'是否将设备'+ scope.row.equipmentNo +'设置为测试设备？'" >
            <el-button type="text" slot="reference">否</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" :disabled="scope.row.fenpei === '1'" v-hasPermi="['equipment:info:edit']" >修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" :disabled="scope.row.fenpei === '1'" v-hasPermi="['equipment:info:remove']" >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改设备信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="设备类型" prop="equipmentType">
          <el-select v-model="form.equipmentType" placeholder="请选择设备类型" style="width: 100%;">
            <el-option v-for="dict in dict.type.equipment_type" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="设备编号" prop="equipmentNo">
          <el-input v-model="form.equipmentNo" placeholder="请输入设备编号" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 设备导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body :close-on-click-modal="false">
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls"
        :headers="upload.headers" :action="upload.url" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 设备分配 -->
    <el-dialog title="分配设备" :visible.sync="change.open" width="400px" append-to-body :close-on-click-modal="false">
      <el-form ref="distributionForm" :model="change.form" :rules="change.rules" label-width="80px">
        <el-form-item label="分配医院" prop="hospitalId">
          <el-select v-model="change.form.hospitalId" @change="getDeptOptions" placeholder="请选择医院" filterable style="width: 100%;">
            <el-option v-for="data in change.hospitalOptions" :key="data.value" :label="data.label" :value="data.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="分配科室" prop="deptId">
          <el-select v-model="change.form.deptId" placeholder="请选择科室" filterable style="width: 100%;">
            <el-option v-for="data in change.deptOptions" :key="data.value" :label="data.label" :value="data.value" />
          </el-select>
        </el-form-item>

        <div v-show="change.tj01EquipmentNoArr.length > 0 && change.tj02EquipmentNoArr.length > 0" style="margin-top: 10px;">
          <el-divider content-position="left">以下参数仅对睡眠监测垫生效</el-divider>
        </div>
        <el-form-item v-show="change.tj01EquipmentNoArr.length > 0" label="租用次数" prop="usageFrequency">
          <el-input-number v-model="change.form.usageFrequency" controls-position="right" :min="1" style="width: 100%;" />
        </el-form-item>
        <el-form-item v-show="change.tj01EquipmentNoArr.length > 0" label="提醒阈值" prop="reminderThreshold">
          <el-input-number v-model="change.form.reminderThreshold" controls-position="right" :min="1" style="width: 100%;" />
        </el-form-item>

        <div v-show="change.tj01EquipmentNoArr.length > 0 && change.tj02EquipmentNoArr.length > 0" style="margin-top: 10px;">
          <el-divider content-position="left">以下参数仅对多参数监测仪生效</el-divider>
        </div>
        <el-form-item v-show="change.tj02EquipmentNoArr.length > 0" label="是否测试" prop="testFlag">
          <el-radio-group v-model="change.form.testFlag">
            <el-radio label="1">是</el-radio>
            <el-radio label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitDistributionForm">确 定</el-button>
        <el-button @click="distributionCancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listInfo,
  getInfo,
  delInfo,
  addInfo,
  updateInfo,
  reqDistribution,
  reqRecovery,
  changeTestStatus
} from "@/api/business/equipment";
import {getToken} from "@/utils/auth";
import {getOptionData} from "@/api/business/hospital";
import {getDeptOptionData} from "@/api/business/dept";

export default {
  name: "EquipmentInfo",
  dicts: ['equipment_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      infos: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备信息表格数据
      infoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        no: null,
        type: null,
        fp: null,
        hospitalId: null,
        deptId: null
      },
      // 医院下拉数据
      hospitalOptions: [],
      // 科室下拉数据
      deptOptions: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        equipmentType: [
          { required: true, message: "设备类型不能为空", trigger: "blur" }
        ],
        equipmentNo: [
          { required: true, message: "设备编号不能为空", trigger: "blur" }
        ],
      },
      // 设备导入参数
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/equipment/info/importData"
      },

      // 设备分配与回收相关参数
      change: {
        // 类型
        type: '',
        // 弹框
        open: false,
        // 医院下拉数据
        hospitalOptions: [],
        // 科室下拉数据
        deptOptions: [],
        tj01EquipmentNoArr: [],
        tj02EquipmentNoArr: [],
        tj03EquipmentNoArr: [],
        // 表单信息
        form: {},
        // 表单校验
        rules: {},
      },
    };
  },
  created() {
    this.getHospitalData();
    this.getList();
  },
  methods: {
    getHospitalData (){
      getOptionData().then(response => {
        this.hospitalOptions = response.data;
      });
    },
    getDeptData (val){
      this.queryParams.deptId = '';
      if(! val) {
        this.deptOptions = [];
      } else {
        getDeptOptionData(val).then(response => {
          this.deptOptions = response.data;
        });
      }
    },
    queryHospitalChange(val){
      this.getDeptData(val);
      this.handleQuery();
    },

    /** 查询设备信息列表 */
    getList() {
      this.loading = true;
      listInfo(this.queryParams).then(response => {
        this.infoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        equipmentNo: null,
        equipmentType: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.infos = selection;
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加设备信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      getInfo(row.id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改设备信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateInfo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addInfo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('该操作不可撤销，是否确认删除所选设备？').then(function() {
        return delInfo(row.id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('equipment/info/export', {
        ...this.queryParams
      }, `info_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "设备导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('equipment/info/importTemplate', {
      }, `equipment_template_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },

    // 分配（type = distribution）
    // 回收（type = recovery）
    handleBtn(type){
      this.change.type = type;
    },
    isSelectable(row, index) {
      if(this.change.type === "distribution") {
        return row.fenpei === "0";
      }
      if(this.change.type === "recovery") {
        return row.fenpei === "1";
      }
      return false;
    },
    handleChange(){
      if(this.change.type === "distribution") {
        this.change.tj01EquipmentNoArr = [];
        this.change.tj02EquipmentNoArr = [];
        this.change.tj03EquipmentNoArr = [];
        // 睡眠监测垫
        let tj01 = [];
        // 多参数监测仪
        let tj02 = [];
        // 心电血压监测仪
        let tj03 = [];
        for(let i = 0; i < this.infos.length; i++) {
          let info = this.infos[i];
          if(info.type === "TJ01") {
            tj01.push(info.equipmentNo);
            this.change.tj01EquipmentNoArr.push(info.id);
          }
          if(info.type === "TJ02") {
            tj02.push(info.equipmentNo);
            this.change.tj02EquipmentNoArr.push(info.id);
          }
          if(info.type === "TJ03") {
            tj03.push(info.equipmentNo);
            this.change.tj03EquipmentNoArr.push(info.id);
          }
        }

        let msg = "是否确认分配以下所选设备吗？<br/>";
        if(tj01.length > 0) {
          msg += "<b>睡眠监测垫：</b>" + tj01.join("、") + "<br/>";
        }
        if(tj02.length > 0) {
          msg += "<b>多参数监测仪：</b>" + tj02.join("、") + "<br/>";
        }
        if(tj03.length > 0) {
          msg += "<b>心电血压监测仪：</b>" + tj03.join("、") + "<br/>";
        }

        this.$confirm(msg, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          dangerouslyUseHTMLString: true
        }).then(() => {
          getOptionData().then(response => {

            this.change.rules = {
              hospitalId: [
                { required: true, message: "请选择要分配的医院", trigger: "blur" }
              ]
            }
            if(tj01.length > 0) {
              this.change.rules = {
                hospitalId: [
                  { required: true, message: "请选择要分配的医院", trigger: "blur" }
                ],
                usageFrequency: [
                  { required: true, message: "租用次数不能为空", trigger: "blur" }
                ],
                reminderThreshold: [
                  { required: true, message: "提醒阈值不能为空", trigger: "blur" }
                ],
              }
            }

            this.change.hospitalOptions = response.data;
            this.resetDistributionForm();
            this.change.open = true;
          });
        }).catch(() => {
        });
      }

      if(this.change.type === "recovery") {
        let ids = [];
        for(let i = 0; i < this.infos.length; i++) {
          let info = this.infos[i];
          ids.push(info.id);
        }
        reqRecovery(ids).then(response => {
          this.$modal.msgSuccess(response.msg);
          this.handleChangeCancel();
          this.getList();
        });
      }
    },
    getDeptOptions(val){
      if(! val) {
        this.change.deptOptions = [];
      } else {
        getDeptOptionData(val).then(response => {
          this.change.deptOptions = response.data;
        });
      }
    },
    handleChangeCancel(){
      this.change.type = "";
      this.$refs.equipmentTable.clearSelection();
      this.infos = [];
    },
    submitDistributionForm(){
      this.$refs["distributionForm"].validate(valid => {
        if (valid) {
          // 提交分配

          let param = this.change.form;
          param.tj01Id = this.change.tj01EquipmentNoArr.join(",")
          param.tj02Id = this.change.tj02EquipmentNoArr.join(",")
          param.tj03Id = this.change.tj03EquipmentNoArr.join(",")

          reqDistribution(param).then(response => {
            this.$modal.msgSuccess("操作成功");
            this.distributionCancel();
            this.handleChangeCancel();
            this.getList();
          });
        }
      });
    },
    distributionCancel(){
      this.change.open = false;
      this.resetDistributionForm();
    },
    resetDistributionForm(){
      this.change.form = {
        hospitalId: null,
        deptId: null,
        usageFrequency: 40,
        reminderThreshold: 5,
        testFlag: '0',
      };
      this.resetForm("distributionForm");
    },

    // 修改多参数监测仪测试状态
    doChange(hosEqId, testStatus){
      changeTestStatus({id: hosEqId, testFlag: testStatus}).then(response => {
        this.$modal.msgSuccess("修改成功");
        this.getList();
      });
    },
  }
};
</script>
